#!/usr/bin/env python

import numpy as np
import os, serial,time,socket,sys,json,logging,requests,getopt
from meas_data import meas_data
# import the server implementation
# import ADC
sensor="vedirect"
pathname = os.path.dirname(sys.argv[0])        
abspath=os.path.abspath(pathname)

idfile=abspath+"/id.json"
id_conf=0
try:
	idf=open(idfile,"r")
	id_conf=json.load(idf)['id']
	idf.close()
except:
	id_conf=0

configfile=abspath+"/config.json"
try:
	cf=open(configfile,"r")
except:
	cf=open(configfile+".template","r")

log_conf=json.load(cf)
cf.close()

channel_names=[]
channel_info={}

parameter={"device":socket.gethostname(),"deviceid":"FF","mean_count":5,"ring_length":10,"wait":0.5,"cycle":10,"check_last":5,"check_last_shrinking":0.9,"gpg_keyid":"","digits":3,"store_dir":"/home/pi/log/","multiplicator":1000,"sigma":3,"sensor":sensor}
for n in parameter:
  if n in log_conf:
    parameter[n]=log_conf[n]


# declare ve mppt
bve=False
if sensor in log_conf:
  from vedirect import vedirect
  bmqtt=False
  if "mqtt" in log_conf:
    bmqtt=True
    lcmq=log_conf['mqtt']
    mbroker=""
    if 'broker' in lcmq:
      mbroker=lcmq['broker']
    else:
      bmqtt=False
    mport=1883
    if 'port' in lcmq:
      mport=lcmq['port']  
  if "sqlserver" in log_conf:
    hostname="localhost"
    port=8080
  bve=True
  if "enable" in log_conf[sensor]:
    if log_conf[sensor]['enable'] == 0:
      bve=False
  if "port" in log_conf[sensor]:
    bve_port=log_conf[sensor]['port']
  else:
    bve_port='/dev/serial/by-id/usb-VictronEnergy_BV_VE_Direct_cable_VE1SSBVT-if00-port0'
  print(bve_port)
  try:
    ve=vedirect(bve_port,60)
  except:
    bve=False
  else:
    tsl_sigma=parameter['sigma']
    parameter["i2c"]=0
    for n in parameter:
      if n in log_conf['vedirect']:
        parameter[n]=log_conf['vedirect'][n]
    if "sigma" in log_conf['vedirect']:
      parameter['sigma']=int(log_conf['vedirect']['sigma'])
      if parameter['sigma'] < 1:
        parameter['sigma']=1
    varnames={"volt_bat":"V","volt_arr":"VPV","amp_bat":"I","watt":"PPV","days":"HSDS"}
    varnamess={"volt_bat":"voltage","volt_arr":"voltage","amp_bat":"current","watt":"power","days":"days"}
    mult={"volt_bat":1000,"volt_arr":1000,"amp_bat":1,"watt":1,"days":1}
    sensorn={"volt_bat":"VE_Battery","volt_arr":"VE_Array","amp_bat":"VE_Battery","watt":"VE_Battery","days":"VE_Array"}
    for i in varnames:
      parch=parameter
      parch["var_name"]=i
      parch["multiplicator"]=mult[i]
      channel_info[i]={"meas_data": meas_data(parch)}
      if bmqtt and ("mqtt" in log_conf[sensor]):
        channel_info[i]['meas_data'].set_mqtt(broker=mbroker,port=mport)
      if "sqlserver" in log_conf:
        channel_info[i]['meas_data'].set_sql(host=hostname,port=port)


if bve:
  while True:
  
    try:
      vedata=ve.read_data_single()
    except:
      print("could not read VE")
    else:
      for i in ("volt_bat","volt_arr","amp_bat"):
        vedata[varnames[i]]=float(vedata[varnames[i]])/1000
      for i in varnames:
        cn=varnames[i]
        if cn in vedata:
          channel_info[i]['meas_data'].append(vedata[cn])

    time.sleep(parameter['wait'])


# close the client
print("done")


